// import Share from './components';
import React from 'react';
import { observer, inject } from 'mobx-react';
import { Route, withRouter } from 'react-router-dom';
import { RouteLayout } from 'weaver-mobile-page';
import { Icon, List, Checkbox, ActivityIndicator, Result, Avatar, Tools } from 'weaver-mobile';
import AddPerson from './components/index';
import classnames from 'classnames';
import Footer from './components/Footer';
import './style/index.less';
import { userType } from '../../components/form/permission/type';

const { USER, CHATGROUP } = userType;
const getLabel = Tools.getLabel;
const CheckboxItem = Checkbox.CheckboxItem;

@inject('shareStore')
@withRouter
@observer
export default class ShareView extends React.Component {

  static defaultProps = {
    prefixCls: 'wm-share',
    outClassName: '',
  }

  componentWillMount() {
    const { init } = this.store;
    init();
  }

  constructor(props) {
    super(props);

    this.store = props.shareStore;
    const { memberList, recentAddList } = this.props;

    recentAddList.forEach(p => {
      let member = null;

      p.isSelect = false;
      member = memberList.find(o => Number(o.id) === Number(p.id));
      member && (p.isSelect = true);
    })

    this.state = {
       recentAddList,
       memberList
    };
  }

  onChange = (obj) => {
    let { recentAddList, memberList } = this.state;
    
    if(obj.isSelect){
      memberList.forEach((ml, index) => {
        Number(ml.id) === Number(obj.id) && (memberList.splice(index, 1))
      })
    }else {
      memberList.push(obj)
    }

    recentAddList.forEach(data => {
      if (Number(data.id) === Number(obj.id)) {
        data.isSelect = !data.isSelect
      }
    });

    this.setState({ recentAddList, memberList })
  }
  onBack = () => {
    window.history.back(-1);
  }

  setMemberList = (list, callback) => this.setState({memberList: list},() => callback && callback()) 

  onSubmit = () => {
    const { memberList } = this.state;
    const { onSubmit, history } = this.props;

    const users = memberList.filter(p => p.type !== CHATGROUP);
    const chatGroup = memberList.filter(p => p.type === CHATGROUP);
    const userIds = users.map(u => u.id);
    const chatGroupIds = chatGroup.map(c => c.id);

    onSubmit([
      {
        memberId: userIds.join(','),
        memberType: USER
      },
      {
        memberId: chatGroupIds.join(','),
        memberType: CHATGROUP
      }
    ]);

    history.push('/form/permission');
  }

  renderChatList = (list, wrapCls) => {
    const chatList = list.map((data, index) => (
      <CheckboxItem key={`checkboxItem_${data.id}`} onChange={() => this.onChange(data)} checked={data.isSelect}>
        <div className={`${wrapCls}-list`} key={`chatItem_${index}`}>
          {<Avatar userId={data.id} /> }
          <div className={`${wrapCls}-list-right ${wrapCls}-list-middle`}>
            {data.lastname}
          </div>
        </div>
      </CheckboxItem>
    ));
    return chatList;
  }

  render() {
    const { chatLoading } = this.store;
    // const { layout, chatList, chatValue, doChatFilter, path, setStoreState, chatLoading, browserHrmStore, isInEM } = this.store;
    const { prefixCls, className } = this.props;
    const wrapCls = classnames(prefixCls, className);
    const { recentAddList, memberList } = this.state;
    const count = memberList.length;
    const renderLoading = (
      <div className={`${wrapCls}-loading`}>
        <ActivityIndicator text="loading..." size="large" />
      </div>
    );
    const renderNoData = (
      <div className={`${wrapCls}-nodata`}>
        <Result
          img={<Icon type="no-data" />}
          message={getLabel(83553, '暂无数据')}
        />
      </div>
    );
    const renderList = () => {
      if (chatLoading) return renderLoading;
      if (recentAddList.length === 0) return renderNoData;
      return this.renderChatList(recentAddList, wrapCls);
    };

    return (
      <RouteLayout>
        <div className='wm-edc-share wm-route-layout' key="shareview">
          <List.Item
            className={`${wrapCls}-chat-item`}
            thumb={<div className={`${wrapCls}-chat-left`}><Icon type="new-chat" /></div>}
            multipleLine
            onClick={() => this.props.history.push(`/form/permission/share/add`)}
          >
            {'选择emessage好友'}
          </List.Item>
          <div className={`${wrapCls}-latest`}>{'最近添加'}</div>
          <div className={`${wrapCls}-chat-list`} >{renderList()}</div>
          <Footer count={count} onSubmit={this.onSubmit} onBack={this.onBack} />
        </div>
        {
          <Route
            key="add"
            path="/form(/permission/|/)share/add"
            render={() => (
              <AddPerson
                {...this.props}
                onSubmit={this.onSubmit}
                memberList={memberList}
                onChange={this.onChange}
                setMemberList={this.setMemberList}
              />
            )}
          />
        }
      </RouteLayout>
    );
  }
}
